#!/bin/bash

if [ $# == 0 ]; then
    day=0
else 
    day=$1
fi

>tmp$$
>tmpcurrent$$
>tmpprior$$
today=`date -d-$"$day"day +%d-%b-%y`

curl -stderr "http://www.covestor.com/rankings/portfolio?showselector=1" |egrep -o "<td>[0-9]+.[0-9]+</td>" |cat -n |sed -e 's/<td>//g' -e 's/<\/td>//g' > tmp$$

curl -stderr "http://www.covestor.com/rankings/portfolio?showselector=1" |egrep -o "/mbr/[a-zA-Z0-9_.-]+" |sed 's/ //g' |uniq |cat -n > tmp1$$

join tmp$$ tmp1$$ > tmprank$$

curl -stderr "http://www.covestor.com/rankings/portfolio?showselector=1" |egrep -o "/mbr/[a-zA-Z0-9_.-]+" |sed 's/ //g' |uniq |while read member
do
    curl -stderr "http://www.covestor.com/$member/holdings"|egrep -v "Tooltip|followers|tracklist|replicate|wishlist" |egrep -o "$member/blog\?stk=[A-Z.]+|$today|<table summary=.+>$" |grep -v "width="   > tmp$$
   
    grep -B 100 sortable tmp$$ |grep -B 1 $today|grep -v $today  >> tmpcurrent$$
    grep -A 100 sortable tmp$$ |grep -B 1 $today|grep -v $today >> tmpprior$$
done

echo "$today's Activity========================" > CovestorList
cat tmpcurrent$$ |grep -v "\-\-" |while read line
do
    member=`echo $line|cut -d'/' -f1-3`
    stock=`echo $line|cut -d'=' -f2|tr [a-z] [A-Z]`
    longshort=`curl -stderr "http://www.covestor.com$member/holdings" |egrep -o ">$stock</a>|long_market|short_market" |grep -A 1 "$stock" |grep -v $stock |sed -e 's/long_market/LONG/g' -e 's/short_market/SHORT/g'`
    rank=`grep $member tmprank$$`
    echo $rank,$stock,$longshort >> CovestorList
done

echo "Prior Activity============================" >> CovestorList
cat  tmpprior$$ |grep -v "\-\-" |while read line
do
    member=`echo $line|cut -d'/' -f1-3`
    stock=`echo $line |cut -d'=' -f2 |tr [a-z] [A-Z]` 
    rank=`grep $member tmprank$$`
    echo $rank,$stock,"SOLD" >> CovestorList
done

cat CovestorList

\rm -f tmpcurrent* tmpprior* tmp$$ tmp1$$ tmprank$$
